<template>
  <select
    class="va-df-input-control"
    :multiple="field.multiple"
    :name="field.name"
    :disabled="disabled"
    @change="onChange">
    <option v-for="(item, index) in dataSource"
            :value="index"
            :selected="isSelected(item)">
      {{getLabel(item)}}
    </option>
  </select>
</template>

<script>
  import _ from 'lodash'
  /*
  * field配置
  *   dataSource
  *   optionLabelProp: string
  *   optionValueProp: string
  *   multiple: boolean
  *   disabled
  *   name: string
  * */
  export default {
    props: {
      value: {},
      field: Object,
      disabled: Boolean,
      dataSource: {
        type: Array,
        default: []
      }
    },
    mounted () {
      this.initComponent()
    },
    watch: {
      dataSource (newV, oldV) {
        if (newV !== oldV) {
          this.initComponent()
        }
      }
    },
    methods: {
      initComponent () {
        if (!this.field.multiple && this.dataSource.length > 0) {
          let optionValueProp = this.field.optionValueProp
          let value = this.value
          let valueMap = _.find(this.dataSource, function (o) { return o[optionValueProp] === value })
          let idx = this.dataSource.indexOf(valueMap)
          if (idx === -1) idx = 0
          let val = this.dataSource[idx]
          if (this.field.optionValueProp) {
            val = _.get(val, this.field.optionValueProp)
          }
          this.$emit('input', val)
        }
      },
      onChange (e) {
        const selectedOptionIdxs = _.map(e.target.selectedOptions, 'value')
        let rstChain
        rstChain = _.chain(this.dataSource)
          .filter(function (item, idx) {
            return _.indexOf(selectedOptionIdxs, idx + '') > -1
          })
        if (!_.isNil(this.field.optionValueProp)) {
          rstChain = rstChain.map(this.field.optionValueProp)
        }
        this.$emit('input', this.field.multiple ? rstChain.value() : rstChain.head().value())
      },
      getLabel (item) {
        if (!_.isNil(this.field.optionLabelProp)) {
          return _.get(item, this.field.optionLabelProp)
        }
        return item
      },
      isSelected (item) {
        if (this.field.multiple) {
          return _.indexOf(this.value, !_.isNil(this.field.optionValueProp) ? _.get(item, this.field.optionValueProp) : item) > -1
        } else {
          return this.value === (!_.isNil(this.field.optionValueProp) ? _.get(item, this.field.optionValueProp) : item)
        }
      }
    }
  }
</script>
